package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登录拦截器
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// log.info("请求进入登录拦截器");
		//判断登录状态
		User user = (User)request.getSession().getAttribute("SESSION_USER");
		if (user != null) {
			//用户存在于session中则已经登录直接放行
			// log.info("用户已经登录");
			UserHolder.set(user);
			return true;
		}
		
		//没有登录直接禁止通行,返回错误
		String json = JSON.toJSONString(ResultInfo.error("user not login"));
		String string = new ObjectMapper().writeValueAsString(ResultInfo.error("NOTLOGIN"));
		
		// log.info("用户未登录");
		
		response.getWriter().write(string);
		return false;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		//请求离开服务器,清除ThreadLocal中用户数据
		UserHolder.remove();
	}
}
